//
//  AppDelegate.m
//  Manager
//
//  Created by 彭凯敏 on 15/8/17.
//  Copyright (c) 2015年 52xiaoluo. All rights reserved.
//

#import "AppDelegate.h"
#import "NetReachability.h"
#import "Startup.h"
#import "MenuTabBar.h"
#import "MobClick.h"
#import "LoginViewController.h"
#import "MsgLogic.h"


@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];

    
    
    [MobClick startWithAppkey:@"55d19736e0f55a0333002554" reportPolicy:BATCH   channelId:@""];
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
    
    
    [[Startup shareInstance] start];
    [[NetReachability shareInstance]registerReach];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    //跳转菜单页面的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(gotoMenuPage) name:@"gotoMP" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(gotoLoginVC) name:@"gotoLogin" object:nil];
    
    
    UIViewController *(^RootVCBlock)(UInt64 number) = ^(UInt64 number)
    {
        return number?[[MenuTabBar alloc]init]:[[LoginViewController alloc]init];
    };
    
    self.window.rootViewController = RootVCBlock([[UserLogic shareInstance]getUserId]);
    
    [self.window makeKeyAndVisible];
    
    if (8.0 <= [[[UIDevice currentDevice] systemVersion] floatValue]) {
        
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings
                                                                             settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
                                                                             categories:nil]];
    } else {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
    }
    
    if (launchOptions != nil)
    {
        NSDictionary* dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        if (dictionary != nil)
        {
            
            //未启动应用时收到通知 操作。
        }
    }
    return YES;
    
}


- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    if (8.0 <= [[[UIDevice currentDevice] systemVersion] floatValue]) {
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
}

- (void)gotoMenuPage
{
    HUDRemove;
    MenuTabBar *tbv = [[MenuTabBar alloc]init];
    self.window.rootViewController = tbv;
}
- (void)gotoLoginVC
{
    LoginViewController *vc = [[LoginViewController alloc]init];
//    self.window.rootViewController = vc;
    [self.window.rootViewController presentViewController:vc animated:YES completion:nil];
    
}
#pragma mark - 消息推送
//获取DeviceToken成功
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSString* token = [NSString stringWithFormat:@"%@",deviceToken];
    
    NSString *string=[[[token description] stringByReplacingOccurrencesOfString:@"<" withString:@""]
                       stringByReplacingOccurrencesOfString:@">" withString:@""];
    [UserLogic shareInstance].token = string;
    DLog("receive device token %@",token);
}

//注册消息推送失败
- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    DLog("receive device token error %@",error);
    
}

//处理收到的消息推送
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    if (!userInfo || userInfo == nil) {
        return;
    }
    NSString *body = userInfo[@"body"];
    if (body) {
        NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:body options:0];
        Packet *packet = [Packet parseFromData:decodedData];
        [[MsgLogic shareInstance] onPushPlain:packet];
    } else {
        DLog("recieve notifcation %@",userInfo);
    }
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    //角标设置为0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
